package tools

import (
	"strconv"
	"time"
)

// GetNow 获取当前日期 年月日 时分秒
func GetNow() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// GetTimestamp 获取当前秒级时间戳 =>
func GetTimestamp() string {
	ts := time.Now().Unix()
	return strconv.FormatInt(ts, 10)
}

// GetMicro 获取当前微秒级时间戳 =>
func GetMicro() string {
	micro := time.Now().UnixMicro()
	return strconv.FormatInt(micro, 10)
}

// GetNano 获取当前纳秒级时间戳 =>
func GetNano() string {
	nano := time.Now().UnixNano()
	return strconv.FormatInt(nano, 10)
}

// FromUnixTime 时间戳(秒级)转字符串日期
func FromUnixTime(ts int64) string {
	return time.Unix(ts, 0).Format("2006-01-02 15:04:05")
}

// StrToTimeStamp 字符格式转时间戳, example: 2023-12, 2023-12-09, 2023-12-09 13:26:00
func StrToTimeStamp(str string) int64 {
	if len(str) == 10 {
		str = str + " 00:00:00"
	}
	if len(str) == 7 {
		str = str + "-01 00:00:00"
	}
	t, err := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local)
	if err != nil {
		return 0
	}
	// 使用 time.Unix() 函数将时间对象转换为时间戳
	timestamp := t.Unix()
	return timestamp
}

// StrToTime 字符格式转时间, example: 2023-12, 2023-12-09, 2023-12-09 13:26:00
func StrToTime(str string) time.Time {
	if len(str) == 10 {
		str = str + " 00:00:00"
	}
	if len(str) == 7 {
		str = str + "-01 00:00:00"
	}
	t, err := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t
}

// LastDayInMonth 获取某个月的最后一天最后一秒的时间格式
func LastDayInMonth(str string) time.Time {
	today := StrToTime(str)
	// 获取下一个月的第一天
	nextMonth := today.AddDate(0, 1, 0)
	firstDayOfNextMonth := time.Date(nextMonth.Year(), nextMonth.Month(), 1, 0, 0, 0, 0, nextMonth.Location())
	// 获取本月最后一天
	lastDayOfThisMonth := firstDayOfNextMonth.Add(-time.Second)
	return lastDayOfThisMonth
}

// GetRangeTime 获取某日期的起始时间
func GetRangeTime(date string) [2]time.Time {
	t := StrToTime(date)
	if t.Unix() < 0 {
		t = time.Now()
	}
	location, _ := time.LoadLocation("UTC")
	t = t.In(location)
	startOfDay := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, location)
	endOfDay := startOfDay.Add((3600*24 - 1) * time.Second)
	return [2]time.Time{
		startOfDay,
		endOfDay,
	}
}

// TimeDiffStr 获取两个时间的差
func TimeDiffStr(t1, t2 time.Time) string {
	ux1 := t1.Unix()
	ux2 := t2.Unix()
	diffSecond := ux2 - ux1
	diffDay := diffSecond / (3600 * 24)
	diffHour := diffSecond % (3600 * 24) / 3600
	diffMinute := diffSecond % 3600 / 60
	diffS := diffSecond % 60
	res := ""
	if diffDay > 0 {
		res += strconv.FormatInt(diffDay, 10) + "天"
	}
	if diffHour > 0 || diffDay > 0 {
		res += strconv.FormatInt(diffHour, 10) + "小时"
	}
	if diffMinute > 0 {
		res += strconv.FormatInt(diffMinute, 10) + "分钟"
	}
	res += strconv.FormatInt(diffS, 10) + "秒"
	return res
}

// TimeDiffSecond 获取两个时间的差的秒数
func TimeDiffSecond(t1, t2 time.Time) int64 {
	ux1 := t1.Unix()
	ux2 := t2.Unix()
	return ux2 - ux1
}
